![]() |
PATH![]() |
![]() ![]() |
You can't declare a property in a handler, although you can refer to a property declared at the top level of the script or script object to which the handler belongs.
Figure 8-3 summarizes the scope of variables declared in a handler. Examples of each form of declaration follow.
Figure 8-3 Scope of variable declarations within a handler
The scope of a global variable declared in a handler is limited to that handler, although AppleScript looks beyond the handler when it tries to locate an earlier occurrence of the same variable. Here's an example.
set currentCount to 10
on increment()
global currentCount
set currentCount to currentCount + 2
end increment
increment() --result: 12
currentCount --result: 12
When AppleScript encounters the currentCount variable within the on increment handler, it doesn't restrict its search for a previous occurrence to that handler but keeps looking until it finds the declaration at the top level of the script. However, references to currentCount in any subsequent handler in the script are local to that handler unless the handler also explicitly declares currentCount as a global variable.
The scope of a variable declaration using the Set command within a handler is limited to that handler:
script Henry
set currentCount to 10
on increment()
set currentCount to 5
end increment
return currentCount
end script
tell Henry to increment() --result: 5
run Henry --result: 10
The scope of the first declaration of the first currentCount variable, at the top level of the script object Henry , is limited to the Run handler for the script object. The scope of the second currentCount declaration, within the on increment handler, is limited to that handler. AppleScript keeps track of each variable independently.
The scope of a local variable declaration in a handler is limited to that handler, even if the same identifier has been declared as a property at a higher level in the script:
property currentCount : 10
on increment()
local currentCount
set currentCount to 5
end increment
increment() --result: 5
currentCount --result: 10